#include "qtcpthreadbase.h"
#include <QDebug>
#include <QDateTime>
#include <QEventLoop>

QTcpThreadBase::QTcpThreadBase(QObject *parent)
    : QObject(parent)
{
    m_bStopWorkThread = true;
    //connect(this, &QThreadBase::sigStartWorkProc, this, &QThreadBase::slotWorkProc);
    moveToThread(&m_thread);
}

QTcpThreadBase::~QTcpThreadBase()
{
}

//线程是否关闭
bool QTcpThreadBase::isStop()
{
    return m_bStopWorkThread;
}

void QTcpThreadBase::startWorkThread(int nWaitTime)
{    
    //2024-11-19 jhb++ 兼容麒麟系统，主程序与库都使用此线程基类，需用以下方式连接信号槽
    connect(this, SIGNAL(sigStartWorkProc()), this, SLOT(slotWorkProc()));
    //qDebug() << "connect signal slot -- " << bRet;
    m_bStopWorkThread = false;
    m_thread.start();
    threadStart();
    if(0 == nWaitTime) emit sigStartWorkProc();
    else QTimer::singleShot(nWaitTime, this, SLOT(slotWorkProc()));
}

void QTcpThreadBase::stopWorkThread()
{
    //已关闭，不重复关闭
    if(m_bStopWorkThread) return;
    //线程置为关闭
    m_bStopWorkThread = true;
    //线程关闭通知
    threadStop();
    //断开信号槽连接
    disconnect(this, SIGNAL(sigStartWorkProc()), this, SLOT(slotWorkProc()));
    //退出线程
    m_thread.quit();
    //qDebug() << this << QDateTime::currentDateTime().toString("hh:mm:ss:zzz");
    //等待线程退出
    if (false == m_thread.wait())
    {
        //m_thread.terminate();//此函数会导致程序崩溃 暂时注释
    }
    //qDebug() << QDateTime::currentDateTime().toString("hh:mm:ss:zzz");
}

//线程循环  nWaitTime|下次线程循环到来的时间，单位：毫秒 (暂时未使用)
void QTcpThreadBase::threadCirculate(int nWaitTime)
{
    if (true == m_bStopWorkThread) return;
    int nWaitTemp = 50;
    for (int i = nWaitTemp; i <= nWaitTime; i+= nWaitTemp)
    {
        if (true == m_bStopWorkThread) return;
        QEventLoop loop;
        QTimer::singleShot(nWaitTemp, &loop, SLOT(quit()));
        loop.exec();
    }
    //slotWorkProc();
    QTimer::singleShot(50, this, SLOT(slotWorkProc()));
}

//线程休眠,nWaitTime:ms
void QTcpThreadBase::threadSleep(int nWaitTime)
{
    int nWaitTemp = 50;
    for (int i = nWaitTemp; i <= nWaitTime; i+= nWaitTemp)
    {
        if (true == m_bStopWorkThread) return;
        QEventLoop loop;
        QTimer::singleShot(nWaitTemp, &loop, SLOT(quit()));
        loop.exec();
    }
}

//线程开启通知
void QTcpThreadBase::threadStart()
{
}

//线程结束通知
void QTcpThreadBase::threadStop()
{
}
